package com.gdkm.database.holder;

import com.gdkm.database.enums.DataSourceEnum;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Random;

/**
 * @author HD-0078 杨炜耀
 * @date 2021-5-6 16:30
 */
public class DataSourceRouter extends AbstractRoutingDataSource {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.datasource.num}")
    private int num;

    /**
     * 最终的determineCurrentLookupKey返回的是从DataSourceContextHolder中拿到的,因此在动态切换数据源的时候注解
     * 应该给DataSourceContextHolder设值
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DataSourceContextHolder.get();
        if(DataSourceEnum.isSlave(typeKey)){
            // 使用随机数决定使用哪个读库
            Random random = new Random();
            int randomNum = random.nextInt(num) + 1;
            logger.info("random use slave-" + randomNum + ".");
            return DataSourceEnum.SLAVE.getDataSourceName() + randomNum;
        }
        logger.info("use master. sourceName:{}", typeKey);
        return typeKey;
    }
}
